package commRedisService

import (
	"errors"
	"gitee.com/fierce_wolf/go-fox-edge-common/commEntity"
	"time"
)

func (e *RedisService) reloadRedisService() bool {
	reloaded := false
	if e.isNeedLoad() {
		err := e.loadAgileEntities()
		if err != nil {
			return false
		}

		reloaded = true
	}

	e.SetInited()
	return reloaded
}

func (e *RedisService) updateRedisService() bool {
	if e.isNeedSave() {
		// 同步到redis
		err := e.saveAgileEntities()
		if err != nil {
			// 数据结构发生了变化，旧数据格式不匹配，需要清空缓存，等待下一次发布
			//e.cleanAgileEntities()
			return false
		}

		return true
	}

	return true
}

func (e *RedisService) UpdateEntity(entity commEntity.IEntity) error {
	key := entity.MakeServiceKey()
	existEntity := e.getEntityByKey(key)
	if existEntity == nil {
		return errors.New("指定的Entity不存在")
	}

	e.putEntity(key, entity)
	return nil
}

func (e *RedisService) PutEntity(entity commEntity.IEntity) {
	key := entity.MakeServiceKey()

	e.putEntity(key, entity)
}

func (e *RedisService) putEntity(key string, entity commEntity.IEntity) {
	if entity == nil || entity.GetBaseEntity() == nil {
		panic("entity.BaseEntity不能为空：" + key)
	}

	e.setEntityByKey(key, entity)
	e.setAgileByKey(key, time.Now().UnixMilli())
	e.setNeedSave(true)
}

func (e *RedisService) DeleteEntity(key string) {
	e.delEntity(key)
}

func (e *RedisService) delEntity(key string) {

	e.delEntityByKey(key)
	e.delAgileByKey(key)
	e.setNeedSave(true)
}
